package cn.edu.jxau.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;

public class Main {

	public static void main(String[] args) {

		final int m = 3;
		List<Integer> list = new ArrayList<>();
		Collections.addAll(list, 0, 1, 2, 3, 4);
		Iterator<Integer> iterator = new CyclicIterator<>(list);
		int i = 0;
		while (iterator.hasNext()) {
			iterator.next();
			i++;
			if (i == m) {
				iterator.remove();
				i = 0;
			}
		}
		System.out.println(list);
	}
}

class CyclicIterator<T> implements Iterator<T> {

	public List<T> list;
	public int cur;
	public int removeIndex;

	public CyclicIterator(List<T> list) {
		Objects.requireNonNull(list, "参数list不能为null");
		this.list = list;
		removeIndex = -1;
	}

	@Override
	public boolean hasNext() {
		return list.size() > 1;
	}

	@Override
	public T next() {
		if (!hasNext()) {
			throw new NoSuchElementException("迭代器已迭代完全");
		}
		removeIndex = cur;
		cur = (cur == list.size() - 1 ? 0 : cur + 1); // 可能会重绕list
		T item = list.get(cur);
		return item;
	}

	@Override
	public void remove() {

		if (removeIndex < 0) {
			throw new IllegalStateException("迭代器失效");
		}
		System.out.println("remove " + list.remove(removeIndex));
		if (removeIndex < cur) { // 会影响cur
			cur--;
		}
		removeIndex = -1;
	}
}